<template>
  <!-- 地址列表 -->
  <div class="addressList">
    <van-address-list v-model="chosenAddressId" :list="list" @add="onAdd" @edit="onEdit" @select="onSelect" />
    <!-- 地址编辑弹出层 -->
    <van-popup v-model="showEdit" position="top" :overlay="true">
      <van-address-edit :area-list="areaList" :address-info="addressInfo" show-delete @save="onSave" @delete="onDelete" />
    </van-popup>
  </div>
</template>

<script>
import axios from "axios";
import areaList from "../../utils/area";
import { addressList } from "../../api/getDatas";
export default {
  data() {
    return {
      chosenAddressId: "",
      list: [],
      searchResult: [],
      showEdit: false,
      areaList: areaList,
      addressInfo: {}
    };
  },

  methods: {
    // 新增地址
    onAdd() {
      this.showEdit = true;
      this.addressInfo = {};
    },
    onSelect() {
      this.$router.back();
    },
    // 修改地址
    onEdit(item, index) {
      this.showEdit = true;
      // 设置初始值
      let address = {
        id: item.id,
        name: item.name,
        tel: item.tel,
        province: item.province,
        city: item.city,
        county: item.district,
        areaCode: "110105",
        is_default: item.is_default,
        addressDetail: item.address
      };
      this.addressInfo = address;
    },
    // 保存地址
    onSave(item) {
      console.log(item);
    },
    // 删除地址
    onDelete(item) {
      console.log(item);
    },

    // 初始化数据
    initData() {
      addressList().then(res => {
        let addressList = res.data.data;
        let address = {};
        addressList.forEach(el => {
          address = {
            id: el.address_id,
            name: el.name,
            tel: el.mobile,
            province: el.province,
            city: el.city,
            district: el.district,
            is_default: el.is_default,
            area_code: el.district_id,
            address:
              el.province + " " + el.city + " " + el.district + " " + el.address
          };
          if (el.is_default === "1") {
            this.chosenAddressId = el.address_id;
          }
          this.list.push(address);
        });
      });
    }
  },
  created() {
    this.initData();
  }
};
</script>

<style lang="less">
.editAddress {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 10000;
  background-color: #f1f2f6;
}

.van-button {
  .van-button__text {
    justify-content: center;
  }
}
.van-address-list__add {
  z-index: 1000 !important;
}
</style>

